//
//  SNSportViewController.m
//  project
//
//  Created by 张淋 on 2019/5/31.
//  Copyright © 2019 黄建华. All rights reserved.
//

#import "SNSportViewController.h"
#import "project-Bridging-Header.h"
#import "SNSportChartSelectView.h"
#import "SNSportTableViewCell.h"
#import "SportModeModel.h"

@interface SNSportViewController ()<ChartViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, assign) BOOL isPushDetail;    // 本周可以进入详细的天
@property (nonatomic, strong) PieChartView *chartView;
@property (nonatomic, strong) SNSportChartSelectView *selectTypeView;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) NSMutableArray* searchResultArray;
@property (nonatomic, strong) UITableView *sportsTab;
@property (nonatomic, assign) SelectDateType type;

@end

@implementation SNSportViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BBIGLIGHTCOLOR;
    _isPushDetail = YES;
    _searchResultArray = [NSMutableArray array];
    _type = SelectDateWeek;
    [self initHeaderView];
    // 默认显示本周
    [self selectType:SelectDateWeek];
}

- (void)initHeaderView {
    // 选择视图
    _selectTypeView = [[SNSportChartSelectView alloc] initWithFrame:SNFRAME((HHHWIDTH - 210)/2.0, 33 + 5 + FitSimpleIpx(0, 20), 210, 27)];
    _selectTypeView.center = CGPointMake(self.view.centerX, self.leftButton.centerY);
    [self.view addSubview:_selectTypeView];
    
    __weak typeof(self) weakSelf = self;
    _selectTypeView.selectType = ^(SelectDateType type) {
        [weakSelf selectType:type];
    };
    
    // 返回按钮
    UIButton *stepDetailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    stepDetailButton.frame = SNFRAME(5, 30 + FitSimpleIpx(0, 20), 50, 50);
    [stepDetailButton setImageNormal:@"进入"];
    stepDetailButton.center = CGPointMake(25, self.leftButton.centerY);
    [stepDetailButton addTarget:self
                         action:@selector(backView)
               forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stepDetailButton];
    
    // 分割线
//    SNShadowView *shadowLine = [[SNShadowView alloc] init];
//    shadowLine.frame = SNFRAME(0,20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
//    [shadowLine showWithType:1];
//    [self.view addSubview:shadowLine];
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
    
    // 第二级按钮返回
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setImage:[UIImage image:@"左"] forState:UIControlStateNormal];
    [_backBtn addTarget:self action:@selector(backBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_backBtn setFrame:CGRectMake(0, shadowLine.bottom + 5, 33, 33)];
    _backBtn.hidden = YES;
    [self.view addSubview:_backBtn];
    
    // 时间
    _selectDateLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(_backBtn.right + 10, shadowLine.bottom + 9, 200, 20)];
    _selectDateLabel.textAlignment = NSTextAlignmentLeft;
    _selectDateLabel.textColor     = SNCOLORBLACK;
    _selectDateLabel.font          = SNSFONT(14.0);
    [self.view addSubview:_selectDateLabel];
    
    // 饼形图
    _chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, _selectDateLabel.bottom + 5, screenWidth, 230)];
    [self.view addSubview:_chartView];
    
    [self setupPieChartView:_chartView];
    _chartView.legend.enabled = NO;
    _chartView.delegate = self;
    
    // 饼形图数据
    [_chartView animateWithYAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
    
    // 分割线
    SNShadowView *shadowLine1 = [[SNShadowView alloc] init];
    shadowLine1.frame = SNFRAME(0,_chartView.bottom, HHHWIDTH, 0);
    [shadowLine1 showWithType:1];
    [self.view addSubview:shadowLine1];
    
    // 表视图
    _sportsTab = [[UITableView alloc] initWithFrame:CGRectMake(0,shadowLine1.bottom +2, screenWidth, screenHeight - shadowLine1.bottom) style:UITableViewStylePlain];
    [_sportsTab registerNib:[UINib nibWithNibName:NSStringFromClass([SNSportTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    _sportsTab.tableHeaderView = [[UIView alloc] init];
    _sportsTab.tableFooterView = [[UIView alloc] init];
    _sportsTab.delegate = self;
    _sportsTab.dataSource = self;
    _sportsTab.allowsSelection = NO;
    [self.view addSubview:_sportsTab];
}

#pragma mark --UITableViewDelegate  UITableViewDataSource--

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchResultArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SNSportTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setupModel:_searchResultArray[indexPath.row] selectType:_type];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 87;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1);
//    //x和y的最终值为1
//    [UIView animateWithDuration:1 animations:^{
//        cell.layer.transform = CATransform3DMakeScale(1, 1, 1);
//    }];

    CATransform3D transform = CATransform3DIdentity;
    transform = CATransform3DRotate(transform, 0, 0, 0, 1);//渐变
    transform = CATransform3DTranslate(transform, -200, 0, 0);//左边水平移动
    transform = CATransform3DScale(transform, 0, 0, 0);//由小变大
    cell.layer.transform = transform;
    cell.layer.opacity = 0.0;
    [UIView animateWithDuration:0.6 animations:^{
        cell.layer.transform = CATransform3DIdentity;
        cell.layer.opacity = 1;
    }];
}

#pragma mark --action---

- (void)backView {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backBtnClicked:(UIButton *)sender {
    _isPushDetail = YES;
    _backBtn.hidden = YES;
    [self selectType:SelectDateWeek];
    [_chartView animateWithYAxisDuration:1.4];
}

#pragma mark --选择视图按钮操作切换--

- (void)getDataFromDBWith:(SelectDateType)atype {
    _type = atype;
    [_searchResultArray removeAllObjects];
    if (atype == SelectDateWeek) {
        [_searchResultArray addObjectsFromArray:[SportModeModel getSportModeDataWithType:atype]];
    } else {
        
    }
    NSArray *array = [SportModeModel getSportModeDataWithType:atype];
    if (array.count == 0) {
        _chartView.noDataText = SN_Text(@"暂无数据");
    }
    NSMutableArray *ratioArray = [NSMutableArray array];
    for (int i = 0; i < SPORTMODENUM; i ++) {
        NSDictionary *dic = [SportModeModel getEachSportModeData:i slectType:atype];
        NSLog(@"i:%d,dic:%@",i,dic);
        if ([dic[@"ratio"] doubleValue] != 0) {
            [ratioArray addObject:dic];
        } else {
            
        }
        
        if (atype == SelectDateMonth || atype == SelectDateThreeMonths) {
            NSArray *arr = dic[@"array"];
            if (arr.count != 0) {
                for (SportModeModel *model in arr) {
                    NSLog(@"model.startTime:%@",model.startTime);
                    [_searchResultArray addObject:model];
                }
            }
        } else {
            
        }
    }
    // 刷新表视图数据
    [_sportsTab reloadData];
    [self setDataArray:ratioArray isShowTime:NO];
}
- (void)getWeekDataDeatil:(NSInteger)mode {
    NSDictionary *dic = [SportModeModel getWeekSportModeDataWithType:mode];
    NSMutableArray *ratioArray = [NSMutableArray array];
    NSArray *array = dic[@"array"];
    for (NSDictionary *dic in array) {
        if ([dic[@"ratio"] doubleValue] != 0) {
            [ratioArray addObject:dic];
        }
    }
    [self setDataArray:ratioArray isShowTime:YES];
    [_searchResultArray removeAllObjects];
    [_searchResultArray addObjectsFromArray:dic[@"totalResult"]];
    [_sportsTab reloadData];
    
    // 求时间总和
    NSMutableArray *timeArray = [NSMutableArray array];
    [timeArray removeAllObjects];
    for (SportModeModel *model in dic[@"totalResult"]) {
        [timeArray addObject:@(model.timeLength)];
    }
    CGFloat timeSum = [[timeArray valueForKeyPath:@"@sum.floatValue"] floatValue];
    // 设置中间的文字
    NSString *totalTime = [SN_PublicClass timeFormatted:timeSum *60];
    // 分
    if ([totalTime contains:@"h"]) {
        _chartView.centerAttributedText = [SN_PublicClass setChartViewCenterText:totalTime allTextFontSize:24 AttributesTextFontSize:16];
    } else {
        // 时 、分
        _chartView.centerAttributedText = [SN_PublicClass attributed:totalTime withFontsize:16 withChangeText1:@"mins"];
    }
}

- (void)selectType:(SelectDateType)type {
    [_searchResultArray removeAllObjects];
    // 本周
    NSString *totalTime = @"";
    if (type == SelectDateWeek) {
        _isPushDetail = YES;
    }
    // 本月
    if (type == SelectDateMonth) {
        _isPushDetail = NO;
    }
    // 三个月内
    if (type == SelectDateThreeMonths) {
        _isPushDetail = NO;
    }
    _backBtn.hidden = YES;
    // 获取数据
    [self getDataFromDBWith:type];
    // 设置中间的文字
    totalTime = [SN_PublicClass timeFormatted:[SportModeModel getTotalSportTime:type] *60];
    // 分
    if ([totalTime contains:@"h"]) {
        _chartView.centerAttributedText = [SN_PublicClass setChartViewCenterText:totalTime allTextFontSize:24 AttributesTextFontSize:16];
    } else {
        // 时 、分
        _chartView.centerAttributedText = [SN_PublicClass attributed:totalTime withFontsize:16 withChangeText1:@"mins"];
    }
    
    [_sportsTab reloadData];
    NSString *time = [[SNPublicClass sharedInstance] showDateWithType:type];
    _selectDateLabel.text = time;
}

#pragma mark - ChartViewDelegate--

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight
{
    if ([entry.data isKindOfClass:[NSDictionary class]]) {
        if (_isPushDetail == YES) {
            _backBtn.hidden = NO;
            _isPushDetail = NO;
            NSDictionary *dic = (NSDictionary *)entry.data;
            int mode = [dic[@"mode"] intValue];
            [self getWeekDataDeatil:mode];
            [_chartView animateWithYAxisDuration:1.4];
            
        } else {
            // 不进入下一级
        }
    } else if([entry.data isKindOfClass:[NSString class]]) {
        // 暂无数不可点击
    } else {
        
    }
}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
{
    NSLog(@"chartValueNothingSelected");
}

#pragma mark --饼形图数据源---

- (void)setDataArray:(NSMutableArray *)ratioArray isShowTime:(BOOL)isShowTime
{
    NSMutableArray *entries = [[NSMutableArray alloc] init];
    [entries removeAllObjects];
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors removeAllObjects];
    

    NSMutableArray *newRatioArray = [NSMutableArray array];
    [newRatioArray removeAllObjects];
    
    NSMutableArray *ratio = [NSMutableArray array];
    // 判断有没有数据源
    if (ratioArray.count != 0) {
        for (NSDictionary *dic in ratioArray) {
            if ([dic[@"ratio"] doubleValue] < 4) {
                [ratio addObject:@(4)];
            } else {
                [ratio addObject:dic[@"ratio"]];
            }
        }
        
        int max =[[ratio valueForKeyPath:@"@max.floatValue"] intValue];
        double sum = [[ratio valueForKeyPath:@"@sum.floatValue"] doubleValue];
        double newMax = max - (sum - 100) ;
        
        for (int i = 0; i < ratio.count; i ++) {
            NSDictionary *dic = (NSDictionary *)ratioArray[i];
            NSMutableDictionary *newDic = [NSMutableDictionary dictionary];
            if ([ratio[i] intValue] == max) {
                [newDic setObject:@(newMax) forKey:@"ratio"];
            } else {
                [newDic setValue:ratio[i] forKey:@"ratio"];
            }
            [newDic setObject:dic[@"array"] forKey:@"array"];
            [newDic setObject:dic[@"mode"] forKey:@"mode"];
            // 本周每天的数据
            if (isShowTime == YES) {
                [newDic setObject:dic[@"time"] forKey:@"time"];
            } else {
                
            }
            [newRatioArray addObject:newDic];
        }
        
        for (int i = 0; i <newRatioArray.count; i++) {
            NSDictionary *dic = newRatioArray[i];
            NSDictionary *realDic = ratioArray[i];
            if ([dic[@"mode"] intValue] == 0) {
                
            } else if ([dic[@"mode"] intValue] == 1) {
                [colors addObject:SNWALKINGCOLOR];
            } else if ([dic[@"mode"] intValue] == 2) {
                [colors addObject:SNRUNNINGCOLOR];
            } else if ([dic[@"mode"] intValue] == 3) {
                [colors addObject:SNCLIMBINGCOLOR];
            } else if ([dic[@"mode"] intValue] == 4) {
                [colors addObject:SNRIDINGCOLOR];
            } else if ([dic[@"mode"] intValue] == 5) {
                [colors addObject:SNTABLETENNISCOLOR];
            } else if ([dic[@"mode"] intValue] == 6) {
                [colors addObject:SNBASKETBALLCOLOR];
            } else if ([dic[@"mode"] intValue] == 7) {
                [colors addObject:SNSOCCERCOLOR];
            }  else if ([dic[@"mode"] intValue] == 8) {
                [colors addObject:SNBADMINTONCOLOR];
            } else if ([dic[@"mode"] intValue] == 9) {
                [colors addObject:SNTREADMILLCOLOR];
            } else if ([dic[@"mode"] intValue] == 10) {
                [colors addObject:SNTENNISCOLOR];
            } else if ([dic[@"mode"] intValue] == 11) {
                [colors addObject:SNSWIMMINGCOLOR];
            } else {
                
            }
            if (isShowTime == NO) {
                [entries addObject:[[PieChartDataEntry alloc] initWithValue:[dic[@"ratio"] doubleValue] label:@"" data:@{@"mode":@([dic[@"mode"] integerValue]),@"ratio":realDic[@"ratio"]}]];
            } else {
                [entries addObject:[[PieChartDataEntry alloc] initWithValue:[dic[@"ratio"] doubleValue] label:@"" data:@{@"time":dic[@"time"],@"ratio":realDic[@"ratio"]}]];
            }
        }
    } else {
        [colors addObject:SNNODATACOLOR];
        [entries addObject:[[PieChartDataEntry alloc] initWithValue:100 label:@"" data:SN_Text(@"暂无数据")]];
    }
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:entries];
    dataSet.selectionShift = 0;
    dataSet.sliceSpace = 1.0;
    dataSet.colors = colors;
    dataSet.valueLinePart1OffsetPercentage = 1.2;
    dataSet.valueLinePart1Length = 0.4;
//    dataSet.valueLinePart2Length = 0.4;
    //dataSet.xValuePosition = PieChartValuePositionOutsideSlice;
    dataSet.yValuePosition = PieChartValuePositionOutsideSlice;
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    ChartDefaultValueFormatter *formatter = [[ChartDefaultValueFormatter alloc] initWithBlock:^NSString * _Nonnull(double value, ChartDataEntry * _Nonnull entry, NSInteger index, ChartViewPortHandler * _Nullable handler) {
        PieChartDataEntry *pieChartDataEntry = (PieChartDataEntry *)entry;
        NSString *des = @"";
        double ratioValue = 0 ;
        NSDictionary *dic = @{};
        if ([pieChartDataEntry.data isKindOfClass:[NSDictionary class]]) {
            dic= (NSDictionary *)pieChartDataEntry.data;
            // 本周、本月、三个月内
            if (isShowTime == NO) {
                int mode = [dic[@"mode"] intValue];
                ratioValue = [dic[@"ratio"] doubleValue];
                if (mode == 0) {
                    
                } else if (mode == 1) {
                    des = SN_Text(@"健步");
                } else if (mode == 2) {
                    des = SN_Text(@"跑步");
                } else if (mode == 3) {
                    des = SN_Text(@"登山");
                } else if (mode == 4) {
                    des = SN_Text(@"骑行");
                } else if (mode == 5) {
                    des = SN_Text(@"乒乓球");
                } else if (mode == 6) {
                    des = SN_Text(@"篮球");
                } else if (mode == 7) {
                    des = SN_Text(@"足球");
                }  else if (mode == 8) {
                    des = SN_Text(@"羽毛球");
                } else if (mode == 9) {
                    des = SN_Text(@"跑步机");
                } else if (mode == 10) {
                    des = SN_Text(@"网球");
                } else if (mode == 11) {
                    des = SN_Text(@"游泳");
                } else {
                    
                }
            } else {
                // 本周详情
                NSString *time = SN_Text(dic[@"time"]);
                ratioValue = [dic[@"ratio"] doubleValue];
                des = time;
            }
            return [NSString stringWithFormat:@"%@ %.1f%@",des,ratioValue,@"%"];
        } else if([pieChartDataEntry.data isKindOfClass:[NSString class]]) {
            // 暂无数据
            des = pieChartDataEntry.data;
            return [NSString stringWithFormat:@"%@",des];
        } else {
            return @"";
        }
    }];
    
    [data setValueFormatter:formatter];
    
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:12.f]];
    [data setValueTextColor:UIColor.blackColor];
    _chartView.data = data;
    [_chartView highlightValues:nil];
    [_chartView animateWithYAxisDuration:1.4];
}

- (void)setupPieChartView:(PieChartView *)chartView
{
    chartView.usePercentValuesEnabled = YES;
    chartView.drawSlicesUnderHoleEnabled = NO;
    chartView.holeRadiusPercent = 0.58;
    chartView.transparentCircleRadiusPercent = 0.61;
    chartView.chartDescription.enabled = NO;
    [chartView setExtraOffsetsWithLeft:5.f top:10.f right:5.f bottom:10.f];
    chartView.drawCenterTextEnabled = YES;
    chartView.drawHoleEnabled = YES;
    chartView.rotationAngle = 0.0;
    chartView.rotationEnabled = YES;
    chartView.highlightPerTapEnabled = YES;
    ChartLegend *l = chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.drawInside = NO;
    l.xEntrySpace = 7.0;
    l.yEntrySpace = 0.0;
    l.yOffset = 0.0;
}


@end
